const express = require('express');
const { ApolloServer } = require('apollo-server-express');

const { typeDefs } = require('./graphql/schemas/schema');
const { resolvers } = require('./graphql/resolvers/resolver');

const app = express();

async function startExpressApolloServer(typeDefs, resolvers) {
  const server = new ApolloServer({
    typeDefs,
    resolvers,
    cors: { credentials: true, allowedHeaders: '', origin: '*' },
  });
  await server.start();

  server.applyMiddleware({ app, path: '/api/graphql' });

  await new Promise((resolve) => app.listen({ port: 3000 }, resolve));
  console.log(`Server ready at http://localhost:3000${server.graphqlPath}`);
  return { server, app };
}

app.get('/rest', function (req, res) {
  res.json({ data: 'api working' });
});

startExpressApolloServer(typeDefs, resolvers);
